package com.taotao.common.service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class RedisService {

	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	
	@Resource(name="stringRedisTemplate")
	private ValueOperations<String, String> valueOperations;
	
	private static final ObjectMapper MAPPER = new ObjectMapper();
	
	/**
	 * 新增或者更新key
	 * @param key
	 * @param value
	 * @throws JsonProcessingException 
	 */
	public void set(String key, Object value) throws JsonProcessingException{
		if(!(value instanceof String)){
			value = MAPPER.writeValueAsString(value);
		}
		this.valueOperations.set(key, (String)value);
	}
	
	/**
	 * 新增或者更新key,设置生存时间
	 * @param key
	 * @param value
	 * @throws JsonProcessingException 
	 */
	public void set(String key, Object value, Long timeout) throws JsonProcessingException{
		if(!(value instanceof String)){
			value = MAPPER.writeValueAsString(value);
		}
		this.valueOperations.set(key, (String)value, timeout, TimeUnit.SECONDS);
	}
	
	/**
	 * 根据key获取value，并反序列化
	 * @param key
	 * @param type
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	public <T> T get(String key, TypeReference<T> type) throws JsonParseException, JsonMappingException, IOException{
		String jsonData = this.valueOperations.get(key);
		if(StringUtils.isEmpty(jsonData)){
			return null;
		}
		if(type == null){
			return (T)jsonData;
		}
		return MAPPER.readValue(jsonData, type);
	}
	
	/**
	 * 根据key删除
	 * @param key
	 */
	public void del(String key){
		this.redisTemplate.delete(key);
	}
	
	/**
	 * 给key设置生存时间
	 * @param key
	 * @param timeout
	 */
	public void expire(String key, Long timeout){
		this.redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
	}
}
